package com.demo.springsecuritystudy.handle;

import lombok.Cleanup;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@Component
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 设置响应的状态码，处理403状态码请求,同时
     * 设置请求头，并返回json字符串
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        @Cleanup PrintWriter writer = httpServletResponse.getWriter();
        writer.write("{\"status\": \"error\", \"message\": \"权限不足请联系管理员\"}");
        writer.flush();
    }
}
